<template>
  <view class="container p_16 redpacket_box" :style="[bgStyle]">
    <view class="fx jcb">
      <navigator
        hover-class="none"
        url="/pages/activities/pages/redpacket_rank?type=share"
      >
        <image
          class="width_154 height_43"
          src="../static/images/redpacket_btn1.png"
          mode=""
        ></image>
      </navigator>
      <navigator
        hover-class="none"
        url="/pages/activities/pages/redpacket_rank?type=custom"
      >
        <image
          class="width_154 height_43"
          src="../static/images/redpacket_btn2.png"
          mode=""
        ></image>
      </navigator>
    </view>
    <view class="mt_144 fc_fff fc fz_16 status1" v-if="status == 1">
      本轮红包会在 {{ dataInfo.beginHour || "" }}-{{ dataInfo.endHour || "" }}
      随机出现
    </view>
    <view
      class="mt_144 fc fz_16 fc_fff status2"
      style="margin-top: 288rpx"
      v-if="status == 2"
    >
      <view class="fx iac jcc">
        剩余可抢时间：<u-count-down
          :time="countdown"
          format="HH:mm:ss"
          @finish="handleRefresh"
        ></u-count-down>
      </view>
      <view class="open_box" @click="handleOpen"></view>
    </view>
    <view
      class="mt_140 fc"
      style="margin-top: 280rpx"
      v-if="status == 4 || status == 3"
    >
      <Divider
        type="red"
        :text="status == 4 ? '本轮未抢到红包' : '本轮抢到红包'"
        :lineCustomStyle="{ height: '8rpx' }"
        :fontCustomStyle="{ fontSize: '48rpx' }"
      />
    </view>
    <view class="mt_8 fx jcc aib" v-if="status == 4">
      <text class="fz_46" style="color: #de3f26">已抢完</text>
    </view>
    <view class="mt_8 fx jcc aib" v-if="status == 3">
      <text class="fz_62" style="color: #de3f26">{{
        dataInfo.userRedPacketRecord.receiveAmount || 0
      }}</text>
      <view
        class="ml_4 height_24 fx aic jcc fc_fff unit_box"
        style="
          background: #d9d9d9 linear-gradient(180deg, #f07650 0%, #dc1927 100%);
        "
      >
        金豆
      </view>
    </view>
    <view
      class="mt_72 fc_fff fc fz_16 status3"
      style="margin-top: 184rpx"
      v-if="status == 3"
    >
      <!-- 下一轮红包会在 {{ dataInfo.beginHour || '' }}-{{ dataInfo.endHour || '' }} 随机出现 -->
      下一轮红包会在 {{ dataInfo.startTimeStr || "" }}-{{
        dataInfo.endTimeStr || ""
      }}
      随机出现
    </view>
    <view
      class="mt_92 fc_fff fc fz_16 status3"
      style="margin-top: 184rpx"
      v-if="status == 4"
    >
      下一轮红包会在 {{ dataInfo.startTimeStr || "" }}-{{
        dataInfo.endTimeStr || ""
      }}
      随机出现
    </view>
    <view
      class="mt_144 fc fz_16 fc_fff status1"
      style="margin-top: 288rpx"
      v-if="status == 5"
    >
      <view class="fx iac jcc">
        本轮红包会在：<u-count-down
          :time="lessMinute"
          format="mm:ss"
          @finish="handleRefresh"
        ></u-count-down
        >后开抢
      </view>
      <!-- <view class="open_box" @click="handleOpen"></view> -->
    </view>
    <view
      class="mt_144 fc_fff fc fz_16 status1"
      style="margin-top: 288rpx"
      v-if="status == 6"
    >
      下一轮红包会在{{ dataInfo.startTimeStr || "" }}-{{
        dataInfo.endTimeStr || ""
      }}随机出现
    </view>
    <template v-if="status == 0">
      <view class="mt_144 fc fz_16 fc_fff" style="margin-top: 288rpx">
        <view class="fx iac jcc">
          剩余可抢时间：<u-count-down
            :time="countdown"
            format="HH:mm"
            @finish="handleRefresh"
          ></u-count-down>
        </view>
      </view>
      <view class="height_239 w100" @click="handleOpen"></view>
      <view>
        <view
          class="br_12 p_16"
          style="
            background: #fbab73
              linear-gradient(180deg, #fffded 0%, #feefce 100%);
          "
        >
          <view class="fc">
            <Divider type="red" text="红包获得记录" />
          </view>
          <view class="pt_12 box height_86">
            <Scroll :options="{ direction: 'up', step: 1 }">
              <view
                class="fx aic jcb mtafter_8"
                v-for="(item, index) in fetchRecord"
                :key="index"
              >
                <view class="fx aic">
                  {{ $utils.hideName(item.customerName || "") }}
                  <text class="ml_4">抢红包获得</text>
                </view>
                <view class="fb fc_primary">
                  {{ item.receiveAmount || 0 }}金豆
                </view>
              </view>
            </Scroll>
          </view>
        </view>
      </view>
      <view class="mt_9">
        <view
          class="br_12 p_16"
          style="
            background: #fbab73
              linear-gradient(180deg, #fffded 0%, #feefce 100%);
          "
        >
          <view class="fc">
            <Divider type="red" text="共享红包记录" />
          </view>
          <view class="pt_12 box height_86">
            <Scroll :options="{ direction: 'up', step: 1 }">
              <view
                class="fx aic jcb mtafter_8"
                v-for="(item, index) in dataInfo.sharedRecord"
                :key="index"
              >
                <view class="fx aic">
                  {{ $utils.hideName(item.customerName || "") }}
                  <text class="ml_4">抢红包获得</text>
                </view>
                <view class="fb fc_primary">
                  {{ item.receiveAmount || 0 }}金豆
                </view>
              </view>
            </Scroll>
          </view>
        </view>
      </view>
    </template>
    <template v-else>
      <!-- <view class="mt_140 fc" style="margin-top: 280rpx;" v-if="status == 5">
				<Divider type="red" :text="status == 1 ? '本轮抢到红包' : '本轮未抢到红包'" :lineCustomStyle="{ height: '8rpx' }"
					:fontCustomStyle="{ fontSize: '48rpx' }" />
			</view> -->
      <!-- <view class="mt_8 fx jcc aib" v-if="status == 5">
				<text class="fz_62" style="color: #DE3F26;">{{ dataInfo.userRedPacketRecord.receiveAmount || 0 }}</text>
				<view class="ml_4 width_24 height_24 br50 fx aic jcc fc_fff"
					style="background: #D9D9D9 linear-gradient(180deg, #F07650 0%, #DC1927 100%);">
					元
				</view>
			</view> -->
      <!-- <view class="mt_8 fx jcc aib" v-if="status == 5">
				<text class="fz_46" style="color: #DE3F26;">已抢完</text>
			</view> -->
      <!-- <view class="mt_119 fc_fff fc fz_16" style="margin-top: 238rpx;" v-if="status == 1">
				本轮红包会在 {{ dataInfo.beginHour || '' }}-{{ dataInfo.endHour || '' }} 随机出现
			</view> -->
      <view class="mt_24">
        <view
          class="br_12 p_16"
          style="
            background: #fbab73
              linear-gradient(180deg, #fffded 0%, #feefce 100%);
          "
        >
          <view class="fc">
            <Divider type="red" text="红包获得记录" />
          </view>
          <view class="pt_12 box height_86">
            <Scroll :options="{ direction: 'up', step: 1 }">
              <view
                class="fx aic jcb mtafter_8"
                v-for="(item, index) in fetchRecord"
                :key="index"
              >
                <view class="fx aic">
                  {{ $utils.hideName(item.userName || "") }}
                  <text class="ml_4">抢红包获得</text>
                </view>
                <view class="fb fc_primary">
                  {{ item.receiveAmount || 0 }} 金豆
                </view>
              </view>
            </Scroll>
          </view>
        </view>
      </view>
      <view class="mt_9">
        <view
          class="br_12 p_16"
          style="
            background: #fbab73
              linear-gradient(180deg, #fffded 0%, #feefce 100%);
          "
        >
          <view class="fc">
            <Divider type="red" text="共享红包记录" />
          </view>
          <view class="pt_12 box height_86">
            <Scroll :options="{ direction: 'up', step: 1 }">
              <view
                class="fx aic jcb mtafter_8"
                v-for="(item, index) in sharedRecord"
                :key="index"
              >
                <view class="fx aic">
                  {{ $utils.hideName(item.userName || "") }}
                  <text class="ml_4">共享红包获得</text>
                </view>
                <view class="fb fc_primary">
                  {{ item.rewardAmount || 0 }} 金豆
                </view>
              </view>
            </Scroll>
          </view>
        </view>
      </view>
    </template>
  </view>
</template>

<script>
import moment from "moment";
import Scroll from "../components/y-scroll-seamless/y-scroll-seamless";
import Divider from "@/components/Divider.vue";
import api from "@/service/config/api";
export default {
  components: {
    Divider,
    Scroll,
  },
  data() {
    return {
      dataInfo: {},
      countdown: 0,
      lessMinute: 0,
      userInfo: this.$storage.getItem("basicUnserInfo") || {},
      customRecord: [],
      shareRecord: [],
      isOpen: false,
      isRefresh: false,
      fetchRecord: [],
      sharedRecord: [],
      timer: null,
      fetchRecord: [],
      sharedRecord: [],
    };
  },
  computed: {
    // 0-活动开始未抢 1-活动结束抢到 2-活动结束未抢到 3-活动未结束抢到 4-活动未结束抢完 5-活动未开始 6-活动未生效
    // 1.时间在活动时间内，但是在拆红包时间外,展示即将开始界面，界面展示本轮红包在几点-几点随机出现
    //2.时间在可拆时间内，并且未拆过红包,界面展示拆，并展示剩余时间，点击拆后，界面展示所拆红包数，以及下一轮红包在几点-几点随机出现
    // 3.时间在可拆时间内，拆过红包，界面展示所拆红包数，以及下一轮红包在几点-几点随机出现
    //4.时间在活动时间内，红包已被抢完，展示已抢完，以及下一轮几点-几点随机出现
    // 5.若红包还剩一分钟出现，则展示倒计时
    // 6.若当前时间还未到可抢时间，则展示下一轮红包在几点出现
    status() {
      console.log("获取到的时间");
      console.log(new Date().getHours);
      console.log();
      // this.getTimeStatus()
      // return 3
      if (!this.dataInfo.redPacket && this.dataInfo.nextRedPacket) {
        return 6;
      }
      if (this.dataInfo && this.dataInfo.redPacket) {
        const grantBeginTime = new Date(
          this.dataInfo.redPacket.grantBeginTime
        ).getTime();
        const grantEndTime = new Date(
          this.dataInfo.redPacket.grantEndTime
        ).getTime();
        const openBeginTime = new Date(
          this.dataInfo.redPacket.openBeginTime
        ).getTime();
        const openEndTIme = new Date(
          this.dataInfo.redPacket.openEndTime
        ).getTime();
        // const now = new Date("2024-02-24 23:30:00").getTime()
        const now = new Date().getTime();
        if (this.dataInfo.redPacket.status == 1) {
          // if(grantBeginTime<=now && grantEndTime>=now) {
          // 	if(now > openEndTIme || (openBeginTime<=now&&openEndTIme>=now && !this.data)) {

          // 	}
          // }
          if (
            (!this.dataInfo.userRedPacketRecord &&
              grantBeginTime <= now &&
              grantEndTime >= now &&
              now > openEndTIme) ||
            (grantBeginTime <= now &&
              grantEndTime >= now &&
              openBeginTime <= now &&
              now <= openEndTIme &&
              !this.dataInfo.redPacket.redPacketsRemnantNum)
          ) {
            console.log("status ==4");
            return 4;
          }
          if (
            grantBeginTime <= now &&
            grantEndTime >= now &&
            (openBeginTime > now || !openBeginTime)
          ) {
            console.log("status==1");
            if (openBeginTime - now <= 60 * 1000) {
              return 5;
            } else {
              return 1;
            }
          }
          if (
            openBeginTime <= now &&
            openEndTIme >= now &&
            this.dataInfo.redPacket.redPacketsRemnantNum &&
            !this.dataInfo.userRedPacketRecord
          ) {
            console.log("status==2");
            return 2;
          }
          if (
            grantBeginTime <= now &&
            grantEndTime >= now &&
            this.dataInfo.userRedPacketRecord
          ) {
            console.log("status==3");
            return 3;
          }

          if (
            now < grantBeginTime ||
            (grantBeginTime <= now && grantEndTime >= now && !openBeginTime)
          ) {
            return 6;
          }
        }
        return 6;
      }
      // if (this.dataInfo) {
      // 	if (this.dataInfo.status == 1) {
      // 		if (this.dataInfo.grantBeginTime > new Date().getTime()) {
      // 			return 5
      // 		} else if (new Date().getTime() > this.dataInfo.grantEndTime) {
      // 			if (this.dataInfo.userRedPacketRecord.receiveAmount) {
      // 				return 1
      // 			} else {
      // 				return 2
      // 			}
      // 		} else {
      // 			if (this.dataInfo.userRedPacketRecord.receiveAmount) {
      // 				return 3
      // 			} else if (!this.dataInfo.redPacketsRemnantNum) {
      // 				return 4
      // 			} else {
      // 				return 0
      // 			}
      // 		}
      // 	}
      // 	return 6
      // }
    },
    bgStyle() {
      if (this.status == 2) {
        return {
          backgroundImage: `url(${
            this.$ossUrl + "/redpacket/redpacket_bg1.png"
          })`,
        };
      } else if (this.status == 1 || this.status == 5 || this.status == 6) {
        return {
          backgroundImage: `url(${
            this.$ossUrl + "/redpacket/redpacket_bg6.png"
          })`,
        };
      } else if (this.status == 4) {
        return {
          backgroundImage: `url(${
            this.$ossUrl + "/redpacket/redpacket_bg3.png"
          })`,
        };
      } else {
        return {
          backgroundImage: `url(${
            this.$ossUrl + "/redpacket/redpacket_bg2.png"
          })`,
        };
      }
    },
  },
  onShow() {
    this.getAllData();
    this.timer = setInterval(() => {
      this.getAllData();
    }, 5000);
  },
  onHide() {
    clearInterval(this.timer);
  },
  onUnload() {
    clearInterval(this.timer);
  },
  methods: {
    isSameDay(date1, date2) {
      return (
        new Date(date1).getFullYear() === new Date(date2).getFullYear() &&
        new Date(date1).getMonth() === new Date(date2).getMonth() &&
        new Date(date1).getDate() === new Date(date2).getDate()
      );
    },
    // 获取显示时间
    getShowTime(start, end) {
      const result = {};
      const now = new Date();
      const startSame = this.isSameDay(start, now);
      const endSame = this.isSameDay(end, now);
      const allSame = this.isSameDay(start, end);
      if (startSame && endSame) {
        result.start = moment(start).format("HH:mm:ss");
        result.end = moment(end).format("HH:mm:ss");
      }
      if (!startSame || !startSame) {
        result.start = moment(start).format("YYYY-MM-DD HH:mm:ss");
        result.end = moment(end).format("HH:mm:ss");
      }
      console.log("格式话的时间");
      console.log(result);
      return result;
    },
    // 获取当前时间是否在时间区间内
    getTimeStatus(startTime, endTime) {
      let now = new Date();
      let startArr = startTime.split(":");
      let endArr = endTime.split(":");
      let startDate = new Date();
      startDate.setHours(startArr[0]);
      startDate.setMinutes(startArr[1]);
      startDate.setSeconds(startArr[2]);
      let endDate = new Date();
      endDate.setHours(endArr[0]);
      endDate.setMinutes(endArr[1]);
      endDate.setSeconds(endArr[2]);
      // 判断当前时间是否在范围内
      if (now >= startTime && now <= endTime) {
        console.log("当前时间在00:00:00-23:59:50范围内");
      } else {
        console.log("当前时间不在00:00:00-23:59:50范围内");
      }
    },
    getAllData() {
      // this.$utils.loading()
      Promise.all([
        this.getData(),
        this.getCustomRecord(),
        this.getShareRecord(),
      ]).finally(() => {
        uni.hideLoading();
      });
    },
    getData() {
      return new Promise((resolve) => {
        api
          .get(
            "/marketing/applet/api/user/red_packet/currentActivity",
            {
              dealerId: this.$store.state.functionRange,
            },
            {
              noHideLoading: true,
            }
          )
          .then((res) => {
            if (!res.data) {
              this.$utils.showToast("红包不定期开发，请稍后再试");
            } else if (!res.data.nextRedPacket) {
              // this.$utils.showToast("红包活动还未开始");
              uni.showToast({
                icon: "none",
                title: "红包活动还未开始",
                duration: 3000,
              });
              setTimeout(() => {
                uni.navigateBack();
              }, 3000);
            } else {
              this.dataInfo = res.data;
              if (this.dataInfo.redPacket) {
                const beginHour = new Date(
                  this.dataInfo.redPacket.grantBeginTime
                ).getHours();
                const beginMinute = new Date(
                  this.dataInfo.redPacket.grantBeginTime
                ).getMinutes();
                const beginSecond = new Date(
                  this.dataInfo.redPacket.grantBeginTime
                ).getSeconds();
                const endHour = new Date(
                  this.dataInfo.redPacket.grantEndTime
                ).getHours();
                const endMinute = new Date(
                  this.dataInfo.redPacket.grantEndTime
                ).getMinutes();
                const endSecond = new Date(
                  this.dataInfo.redPacket.grantEndTime
                ).getSeconds();
                this.dataInfo.beginHour = `${
                  beginHour >= 10 ? beginHour : "0" + beginHour
                }:${beginMinute >= 10 ? beginMinute : "0" + beginMinute}:${
                  beginSecond >= 10 ? beginSecond : "0" + beginSecond
                }`;
                this.dataInfo.endHour = `${
                  endHour >= 10 ? endHour : "0" + endHour
                }:${endMinute >= 10 ? endMinute : "0" + endMinute}:${
                  endSecond >= 10 ? endSecond : "0" + endSecond
                }`;
                console.log("获取红包数据");
                console.log(this.dataInfo);
                this.countdown =
                  new Date(res.data.redPacket.openEndTime).getTime() -
                  new Date().getTime();
                this.lessMinute =
                  new Date(res.data.redPacket.openBeginTime).getTime() -
                  new Date().getTime();
              }
              this.fetchRecord = res.data.fetchRecord || [];
              this.sharedRecord = res.data.sharedRecord || [];
              if (
                res.data.nextRedPacket &&
                res.data.nextRedPacket.grantBeginTime &&
                res.data.nextRedPacket.grantEndTime
              ) {
                const result = this.getShowTime(
                  res.data.nextRedPacket.grantBeginTime,
                  res.data.nextRedPacket.grantEndTime
                );
                this.dataInfo.startTimeStr = result.start;
                this.dataInfo.endTimeStr = result.end;
              }
              // this.countdown = res.data.grantEndTime - new Date().getTime()
            }
          })
          .finally(() => {
            resolve();
          });
      });
    },
    handleRefresh() {
      if (!this.isRefresh) {
        this.isRefresh = true;
        this.getData();
      } else {
        setTimeout(() => {
          this.getData();
        }, 100);
      }
    },
    getCustomRecord() {
      // return new Promise(resolve => {
      // 	api.get('/marketing/web/api/backstage/red_packet/record/my/page', {
      // 		current: 1,
      // 		size: 50,
      // 		receiveType: 1
      // 	}, {
      // 		noHideLoading: true
      // 	}).then(res => {
      // 		this.customRecord = res.data.records || []
      // 	}).finally(() => {
      // 		resolve()
      // 	})
      // })
    },
    getShareRecord() {
      // return new Promise(resolve => {
      // 	api.get('/marketing/web/api/backstage/red_packet/record/my/page', {
      // 		current: 1,
      // 		size: 50,
      // 		receiveType: 2
      // 	}, {
      // 		noHideLoading: true
      // 	}).then(res => {
      // 		this.shareRecord = res.data.records || []
      // 	}).finally(() => {
      // 		resolve()
      // 	})
      // })
    },
    // 开红包
    handleOpen() {
      this.$utils.loading();
      api
        .post("/marketing/applet/api/user/red_packet/open", {
          redPacketId: this.dataInfo.redPacket.id,
          receivePlatform: this.$store.state.functionRange,
          receiveType: 1,
        })
        .then((res) => {
          if (res.data) {
            this.getData();
          }
        });
    },
  },
};
</script>

<style lang="scss">
page {
  background-color: #f94c40;
}
</style>

<style lang="scss" scoped>
.unit_box {
  padding: 5rpx 10rpx;
  border-radius: 24rpx;
}

.container {
  /deep/.u-count-down__text {
    font-size: 32rpx;
    color: #fff;
  }

  // background: url('../static/images/redpacket_bg.png');
  background-size: 100% auto;
  background-repeat: no-repeat;

  .status1 {
    margin-top: 288rpx;
    padding-bottom: 430rpx;
  }

  .status2 {
    margin-top: 288rpx !important;
  }

  .open_box {
    width: 380rpx;
    height: 360rpx;
    margin-left: 150rpx;
    margin-top: 50rpx;
    margin-bottom: 65rpx;
  }

  .status3 {
    margin-bottom: 78rpx;
  }
}

.redpacket_box {
  height: 100vh;
}
</style>
